using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;
using System.IO;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 章节细纲更新服务
    /// 负责在章节完成后更新后续章节的细纲，确保剧情连贯性
    /// </summary>
    public class ChapterOutlineUpdateService
    {
        private readonly ILogger<ChapterOutlineUpdateService> _logger;
        private readonly IAIService _aiService;
        private readonly IDataStorageService _dataStorage;
        private readonly TimelineService _timelineService;

        public ChapterOutlineUpdateService(
            ILogger<ChapterOutlineUpdateService> logger,
            IAIService aiService,
            IDataStorageService dataStorage,
            TimelineService timelineService)
        {
            _logger = logger;
            _aiService = aiService;
            _dataStorage = dataStorage;
            _timelineService = timelineService;
        }

        /// <summary>
        /// 更新后续章节细纲
        /// </summary>
        public async Task<OutlineUpdateResult> UpdateSubsequentChapterOutlinesAsync(
            int projectId, int completedChapterNumber, string completedChapterContent, 
            int updateRange = 3, CancellationToken cancellationToken = default)
        {
            var result = new OutlineUpdateResult();
            
            try
            {
                _logger.LogInformation($"开始更新第{completedChapterNumber}章后续{updateRange}章的细纲");

                // 1. 获取项目信息
                var project = await _dataStorage.GetProjectAsync(projectId);
                if (project == null)
                {
                    result.ErrorMessage = "项目不存在";
                    return result;
                }

                // 2. 获取需要更新的章节范围
                var chaptersToUpdate = await GetChaptersToUpdateAsync(
                    projectId, completedChapterNumber, updateRange);

                if (!chaptersToUpdate.Any())
                {
                    result.IsSuccess = true;
                    result.Message = "没有需要更新的后续章节";
                    return result;
                }

                // 3. 分析已完成章节的影响
                var chapterImpact = await AnalyzeChapterImpactAsync(
                    projectId, completedChapterNumber, completedChapterContent);

                // 4. 逐个更新后续章节细纲
                var updatedOutlines = new List<UpdatedOutline>();
                
                foreach (var chapter in chaptersToUpdate)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    
                    var updatedOutline = await UpdateSingleChapterOutlineAsync(
                        chapter, chapterImpact, completedChapterContent);
                    
                    if (updatedOutline != null)
                    {
                        updatedOutlines.Add(updatedOutline);
                        
                        // 保存更新后的细纲到文件
                        await SaveUpdatedOutlineToFileAsync(project.RootPath, updatedOutline);
                    }
                }

                result.IsSuccess = true;
                result.UpdatedChapterCount = updatedOutlines.Count;
                result.UpdatedOutlines = updatedOutlines;
                result.Message = $"成功更新了{updatedOutlines.Count}个章节的细纲";

                _logger.LogInformation($"后续章节细纲更新完成，更新了{updatedOutlines.Count}个章节");

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新第{completedChapterNumber}章后续细纲失败");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 获取需要更新的章节
        /// </summary>
        private async Task<List<Chapter>> GetChaptersToUpdateAsync(
            int projectId, int completedChapterNumber, int updateRange)
        {
            try
            {
                var allChapters = await _dataStorage.GetChaptersAsync(projectId);
                
                return allChapters
                    .Where(c => c.ChapterNumber > completedChapterNumber && 
                               c.ChapterNumber <= completedChapterNumber + updateRange)
                    .Where(c => string.IsNullOrEmpty(c.Content)) // 只更新未完成的章节
                    .OrderBy(c => c.ChapterNumber)
                    .ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取需要更新的章节失败");
                return new List<Chapter>();
            }
        }

        /// <summary>
        /// 分析已完成章节的影响
        /// </summary>
        private async Task<ChapterImpact> AnalyzeChapterImpactAsync(
            int projectId, int chapterNumber, string chapterContent)
        {
            try
            {
                var prompt = $@"请分析以下第{chapterNumber}章的内容，识别其对后续剧情的影响：

=== 章节内容 ===
{chapterContent.Substring(0, Math.Min(chapterContent.Length, 3000))}...

=== 分析要求 ===
请分析本章对后续剧情可能产生的影响，包括：

1. **剧情发展影响**：本章的事件如何影响主线剧情的发展方向
2. **角色状态变化**：主要角色的状态、能力、关系等变化
3. **世界状态变化**：世界观、势力格局、环境等变化
4. **新增要素**：新出现的人物、物品、地点、线索等
5. **伏笔实现**：本章实现了哪些之前的伏笔
6. **新伏笔设置**：本章为后续剧情埋下了哪些新伏笔
7. **节奏调整**：对整体故事节奏的影响

请按照上述格式详细分析，为后续章节细纲的调整提供依据。";

                var analysisResult = await _aiService.GenerateTextAsync(prompt, 1500, 0.7f);
                
                return new ChapterImpact
                {
                    ChapterNumber = chapterNumber,
                    ImpactAnalysis = analysisResult,
                    AnalyzedAt = DateTime.Now
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"分析第{chapterNumber}章影响失败");
                return new ChapterImpact
                {
                    ChapterNumber = chapterNumber,
                    ImpactAnalysis = "分析失败",
                    AnalyzedAt = DateTime.Now
                };
            }
        }

        /// <summary>
        /// 更新单个章节细纲
        /// </summary>
        private async Task<UpdatedOutline?> UpdateSingleChapterOutlineAsync(
            Chapter chapter, ChapterImpact impact, string completedChapterContent)
        {
            try
            {
                if (string.IsNullOrEmpty(chapter.Summary))
                {
                    _logger.LogWarning($"第{chapter.ChapterNumber}章没有现有细纲，跳过更新");
                    return null;
                }

                var prompt = $@"请根据前一章的完成情况，调整以下章节的细纲：

=== 前一章影响分析 ===
{impact.ImpactAnalysis}

=== 当前章节信息 ===
章节号：第{chapter.ChapterNumber}章
当前细纲：
{chapter.Summary}

=== 调整要求 ===
请根据前一章的实际内容和影响，调整本章细纲，确保：
1. 与前一章的结尾自然衔接
2. 考虑角色状态的变化
3. 反映世界状态的变化
4. 处理新增的剧情要素
5. 保持整体剧情的逻辑性和连贯性
6. 如果前一章的发展与原细纲有偏差，相应调整本章内容

=== 输出格式 ===
请输出调整后的完整章节细纲，保持原有的格式结构。
如果不需要调整，请说明原因并输出原细纲。

调整后的第{chapter.ChapterNumber}章细纲：";

                var updatedOutlineText = await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);

                return new UpdatedOutline
                {
                    ChapterNumber = chapter.ChapterNumber,
                    OriginalOutline = chapter.Summary,
                    UpdatedOutlineText = updatedOutlineText,
                    UpdateReason = $"基于第{impact.ChapterNumber}章的完成情况进行调整",
                    UpdatedAt = DateTime.Now
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新第{chapter.ChapterNumber}章细纲失败");
                return null;
            }
        }

        /// <summary>
        /// 保存更新后的细纲到文件
        /// </summary>
        private async Task SaveUpdatedOutlineToFileAsync(string projectPath, UpdatedOutline updatedOutline)
        {
            try
            {
                var outlineDir = Path.Combine(projectPath, "大纲", "章节细纲");
                Directory.CreateDirectory(outlineDir);

                var fileName = $"第{updatedOutline.ChapterNumber:D3}章_细纲_更新.txt";
                var filePath = Path.Combine(outlineDir, fileName);

                var content = $@"# 第{updatedOutline.ChapterNumber}章细纲（已更新）

## 更新信息
- 更新时间：{updatedOutline.UpdatedAt:yyyy-MM-dd HH:mm:ss}
- 更新原因：{updatedOutline.UpdateReason}

## 更新后细纲
{updatedOutline.UpdatedOutlineText}

## 原始细纲（备份）
{updatedOutline.OriginalOutline}
";

                await File.WriteAllTextAsync(filePath, content);
                _logger.LogDebug($"已保存更新后的细纲: {filePath}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"保存第{updatedOutline.ChapterNumber}章更新细纲失败");
            }
        }

        /// <summary>
        /// 批量更新章节细纲（用于重大剧情变化）
        /// </summary>
        public async Task<OutlineUpdateResult> BatchUpdateChapterOutlinesAsync(
            int projectId, int fromChapter, int toChapter, string majorPlotChange)
        {
            var result = new OutlineUpdateResult();
            
            try
            {
                _logger.LogInformation($"开始批量更新第{fromChapter}-{toChapter}章的细纲");

                var chaptersToUpdate = await _dataStorage.GetChaptersAsync(projectId);
                chaptersToUpdate = chaptersToUpdate
                    .Where(c => c.ChapterNumber >= fromChapter && c.ChapterNumber <= toChapter)
                    .OrderBy(c => c.ChapterNumber)
                    .ToList();

                var updatedOutlines = new List<UpdatedOutline>();

                foreach (var chapter in chaptersToUpdate)
                {
                    var prompt = $@"请根据重大剧情变化调整以下章节细纲：

=== 重大剧情变化 ===
{majorPlotChange}

=== 当前章节信息 ===
章节号：第{chapter.ChapterNumber}章
当前细纲：
{chapter.Summary ?? "无现有细纲"}

请输出调整后的完整章节细纲：";

                    var updatedOutlineText = await _aiService.GenerateTextAsync(prompt, 2000, 0.8f);

                    var updatedOutline = new UpdatedOutline
                    {
                        ChapterNumber = chapter.ChapterNumber,
                        OriginalOutline = chapter.Summary ?? "",
                        UpdatedOutlineText = updatedOutlineText,
                        UpdateReason = "重大剧情变化调整",
                        UpdatedAt = DateTime.Now
                    };

                    updatedOutlines.Add(updatedOutline);
                }

                result.IsSuccess = true;
                result.UpdatedChapterCount = updatedOutlines.Count;
                result.UpdatedOutlines = updatedOutlines;

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量更新章节细纲失败");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                return result;
            }
        }
    }

    /// <summary>
    /// 章节影响分析
    /// </summary>
    public class ChapterImpact
    {
        public int ChapterNumber { get; set; }
        public string ImpactAnalysis { get; set; } = "";
        public DateTime AnalyzedAt { get; set; }
    }

    /// <summary>
    /// 更新后的细纲
    /// </summary>
    public class UpdatedOutline
    {
        public int ChapterNumber { get; set; }
        public string OriginalOutline { get; set; } = "";
        public string UpdatedOutlineText { get; set; } = "";
        public string UpdateReason { get; set; } = "";
        public DateTime UpdatedAt { get; set; }
    }

    /// <summary>
    /// 细纲更新结果
    /// </summary>
    public class OutlineUpdateResult
    {
        public bool IsSuccess { get; set; }
        public int UpdatedChapterCount { get; set; }
        public string Message { get; set; } = "";
        public string ErrorMessage { get; set; } = "";
        public List<UpdatedOutline> UpdatedOutlines { get; set; } = new();
    }
}
